import { apiIheadAdd, apiQmsmgAlllist, apiSfctdPage } from '@/api/url/checkModule';
import { apiJianYan, apiTsgl } from '@/api/url/libraryModules';
import router from '@/router';
import {h, onMounted, reactive, ref} from 'vue';
import { Input, Message, Select } from '@arco-design/web-vue';
import { deepCopy, formatDate, isNullPm } from '@/utils/baseMethods';
import { relativeAddition } from '@/utils/calculationFormula';
import { qmsmgAdd, qmsmgQueryList } from '@api/url/erp/cmsmv';
import notification from '@arco-design/web-vue/es/notification';
// import Pdfh5 from 'pdfh5';
export default function importConfig() {
  const base = reactive<any>({
    pagination: {
      defaultPageSize: 10,
      total: 100, //总条数
      current: 1,
      pageSize: 10,
      showTotal: true,
      showPageSize: true,
      pageSizeOptions: [10, 20, 30, 40, 50],
      hideOnSinglePage: true,
    },
    tabelList: null,
    mesBase: null,
    textYypeList: null,
    numericalTypeList: null,
    modelPm: '文本型',
    columnsA: null,
    columnsB: null,
    inspectionQuantity: 5,
    cloneSteam: null,
    viewPDF: null,
    fromData: {},
    jytz: null,
    jydh: null,
    checkedValue: null,
    checkedUrlValue: null,
    headNpm: {
      people: null,
      udf06: '现场',
    },
    opminac: '现场',
    checky: '',
    reaca: 'NG',
  });

  const init = () => {
    viewInspect();
  };

  const handlePageChange = (page: number) => {
    base.pagination.current = page;
  };
  const handlePageSizeChange = (pageSize: number) => {
    base.pagination.pageSize = pageSize;
  };

  /**
   * @exports viewDetails 查看详情单
   * @param param 品号
   */
  const viewDetails = (param) => {
    // console.log(param)
    router.push({ path: '/inspectionDetails', query: { td001: param.td001.trim(), td002: param.td002.trim() } });
  };

  /**
   * @exports viewInspect 调起检验单
   */
  const viewInspect = (param?): any => {
    const stea = router.currentRoute.value.query;

    if (!isNullPm(param)) base.jydh = param;

    if (!isNullPm(stea.td001)) base.jydh = stea.td001 + '-' + stea.td002 + '-' + stea.te003;

    base.mesBase = [
      {
        label: '品号',
        value: base.cloneSteam?.ta006,
      },
      {
        label: '品名',
        value: base.cloneSteam?.mb002,
      },
      {
        label: '规格',
        value: base.cloneSteam?.mb003,
      },
      {
        label: '数量',
        value: base.cloneSteam?.ta015,
      },
      {
        label: '抽检数',
        value: base.cloneSteam?.udf66,
      },
      {
        label: '样本数',
        value: base.cloneSteam?.udf88,
      },
      {
        label: '检验类型',
        value: router.currentRoute.value.query.TYPENAME,
      },
      {
        label: '工单单别',
        value: base.cloneSteam?.ta001,
      },
      {
        label: '工单单号',
        value: base.cloneSteam?.ta002,
      },
      {
        label: '工艺',
        value: base.cloneSteam?.ta004,
      },
      {
        label: '工艺说明',
        value: base.cloneSteam?.ta024,
      },
      {
        label: '今日到检查',
        value: isNullPm(router.currentRoute.value.query.te003) ? '0001' : router.currentRoute.value.query.te003,
      },
    ];
    console.log(router.currentRoute.value.query);
    base.checky = router.currentRoute.value.query.checky;
    const steamss = {
      article: router.currentRoute.value.query.article,
      code: router.currentRoute.value.query.code,
      startTime: JSON.parse(router.currentRoute.value.query.time as any)[0].replace(/\-/g, ''),
      endTime: JSON.parse(router.currentRoute.value.query.time as any)[1].replace(/\-/g, ''),
      gy: router.currentRoute.value.query.gy,
      checky: router.currentRoute.value.query.checky,
      romm: base.opminac,
    };
    qmsmgQueryList(steamss).then((res: any) => {
      base.cloneSteam = res.data;
      console.log(res);
      base.fromData = res.data.jianYan;
      typeDispenser(res.data.qmsmgList);
      columnsOption();
      getTsglnginx(base.cloneSteam.ta006);
      base.mesBase = [
        {
          label: '品号',
          value: base.cloneSteam.pinhao,
        },
        {
          label: '品名',
          value: base.cloneSteam.pm,
        },
        {
          label: '规格',
          value: base.cloneSteam.gg,
        },
        {
          label: '数量',
          value: base.cloneSteam.ta015,
        },

        {
          label: '检验类型',
          value: router.currentRoute.value.query.checky,
        },
        {
          label: '工单单别',
          value: base.cloneSteam.singetsu,
        },
        {
          label: '工单单号',
          value: base.cloneSteam.odd,
        },
        {
          label: '工艺',
          value: base.cloneSteam.gy,
        },
        {
          label: '工艺说明',
          value: '',
        },
        {
          label: '今日到检查',
          value: '0001',
        },
      ];
    });
  };

  const getTsglnginx = (param) => {
    const steam = {
      MB001: param,
    };
    apiTsgl(steam).then((res: any) => {
      if (res.code == 1) {
        base.jytz = JSON.parse(res.data[0].jyzdslist);
        base.checkedValue = base.jytz[0].name;
        base.checkedUrlValue = base.jytz[0].url;
      }
    });
  };

  /**
   * @exports typeDispenser 文本型数据截取
   */
  const typeDispenser = (steam) => {
    base.numericalTypeList = [];
    base.textYypeList = [];
    console.log(steam);
    steam?.map((res: any,index) => {
      Object.keys(res).map((reb: any) => {
        // console.log(res[reb],reb)
        if (!isNullPm(res[reb]) && typeof res[reb] == 'string') res[reb] = res[reb].trim();
      });
      const axc = {
        ...res,
        ...verifyTheQuantityLoader(res.mg009,res),
      };
      if (res.mg009 === '2') {
        base.textYypeList.push(axc);
      } else {
        base.numericalTypeList.push(axc);
      }
    });
  };

  /**
   * @exports textChange 文本类型数值类型绑定
   */
  const textChange = (param: any) => {
    base.modelPm = param;
  };

  /**
   * @exports verifyTheQuantityLoader 检验数量载入器
   */
  const verifyTheQuantityLoader = (type,res) => {
    const steam = {};

    // for (let a = 1; a <= base.inspectionQuantity; a++) {
    //   steam['vpmk' + a] = null;
    // }

    let relt=localStorage.getItem('qualityAssuranceDetailData');
    if(relt){
      let textList=JSON.parse(relt).textYypeList;
      let numericalList=JSON.parse(relt).numericalTypeList;

      console.log(res);
      console.log(JSON.parse(relt));

      if(type==2){
        let flag=false;
        textList.forEach((item1,index1)=>{
          if(res.mg003==item1.mg003){
            flag=true;
            for (let a = 1; a <= base.inspectionQuantity; a++) {
              steam['vpmk' + a] = textList[index1]['vpmk' + a];
            }
          }
        });

        if(!flag){
          for (let a = 1; a <= base.inspectionQuantity; a++) {
            steam['vpmk' + a] = null;
          }
        }

      }else{
        let flag=false;
        numericalList.forEach((item1,index1)=>{
          if(res.mg003==item1.mg003){
            flag=true;
            for (let a = 1; a <= base.inspectionQuantity; a++) {
              steam['vpmk' + a] = numericalList[index1]['vpmk' + a];
            }
          }
        });

        if(!flag){
          for (let a = 1; a <= base.inspectionQuantity; a++) {
            steam['vpmk' + a] = null;
          }
        }
      }
    }

    return steam;
  };

  /**
   * @exports columnsOption 动态生成数据
   */
  const columnsOption = () => {
    const steamA: any = [
      {
        title: '检验编号',
        dataIndex: 'mg003',
      },
      {
        title: '检验项目',
        dataIndex: 'udf01',
      },
      {
        title: '检验工具',
        dataIndex: 'udf02',
      },
      {
        title: '检验标准',
        dataIndex: 'mg006',
      },
      // {
      //     title: '抽样数',
      //     dataIndex: 'mg016',
      //     render: (data) => {
      //         return parseInt(data.record.mg016)
      //     }
      // },
      {
        title: '检验频次',
        dataIndex: 'udf03',
      },
    ];
    const steamB: any = [
      {
        title: '检验编号',
        dataIndex: 'mg003',
      },
      {
        title: '检验项目',
        dataIndex: 'udf01',
      },
      {
        title: '检验工具',
        dataIndex: 'udf02',
      },

      // {
      //     title: '抽样数',
      //     dataIndex: 'mg016',
      //     render: (data) => {
      //         return parseInt(data.record.mg016)
      //     }
      // },
      {
        title: '检验频次',
        dataIndex: 'udf03',
      },
      // {
      //     title: '关键尺寸',
      //     dataIndex: 'udf05',
      // },
      {
        title: '正公差',
        dataIndex: 'mg012',
        width: 90,
      },
      {
        title: '负公差',
        dataIndex: 'mg013',
        width: 90,
      },
      {
        title: '检验标准',
        dataIndex: 'mg006',
        width: 90,
      },
    ];

    const steamCMM = (max, min, value) => {
      let steam = false;
      if (!isNullPm(value))
        if (max < value || min > value) {
          steam = true;
        }
      return steam;
    };

    const steamCPP = (value): any => {
      let steam = false;
      if (!isNullPm(value) && value == 'NG') steam = true;
      return steam;
    };

    for (let a = 1; a <= base.inspectionQuantity; a++) {
      const steamPm = {
        title: '检号' + a,
        render: (data) => {
          return h(Input, {
            modelValue: data.record['vpmk' + a],
            onInput(value) {
              data.record['vpmk' + a] = value;
            },
            style: {
              backgroundColor: steamCMM(data.record.mg012, data.record.mg013, data.record['vpmk' + a]) ? 'rgb(236, 70, 70)' : '#ededed',
              color: steamCMM(data.record.mg012, data.record.mg013, data.record['vpmk' + a]) ? 'white' : 'black',
              width: '100px',
            },
          });
        },
      };

      const steamPn = {
        title: '检号' + a,
        render: (data) => {
          return h(Select, {
            modelValue: data.record['vpmk' + a],
            options: [
              {
                value: 'OK',
                label: 'OK',
              },
              {
                value: 'NG',
                label: 'NG',
              },
              {
                value: '/',
                label: '/',
              },
            ],
            onChange(value) {
              data.record['vpmk' + a] = value;
            },
            style: {
              backgroundColor: steamCPP(data.record['vpmk' + a]) ? 'rgb(236, 70, 70)' : '#ededed',
              color: steamCPP(data.record['vpmk' + a]) ? 'white' : 'black',
              width: '100px',
            },
          });
        },
      };
      steamA.push(steamPn);
      steamB.push(steamPm);
    }
    base.columnsA = steamA;

    const steamCR = {
      title: 'CR',
      width: 90,
      render: (data) => {
        let mun = 0;
        let count: any = 0;
        Object.keys(data.record).map((rea: any) => {
          if (rea.indexOf('vpmk') != -1) {
            if (!isNullPm(data.record[rea])) {
              mun++;
              count = relativeAddition({ x: count, y: data.record[rea] });
            }
          }
        });

        return mun === 0 ? 0 : count / mun;
      },
    };
    const steamMAX = {
      title: 'MAX',
      width: 90,
      render: (data) => {
        const mun: any = [];
        Object.keys(data.record).map((rea: any) => {
          if (rea.indexOf('vpmk') != -1) {
            let steac = deepCopy(Number(data.record[rea]));
            if (isNullPm(steac)) steac = 0;
            mun.push(steac);
          }
        });

        return mun.reduce((pre, cur) => {
          return Number(pre) >= Number(cur) ? Number(pre) : Number(cur);
        }, 0);
      },
    };
    const steamMIN = {
      title: 'MIN',
      width: 90,
      render: (data) => {
        const mun: any = [];
        let min: any = 0;
        Object.keys(data.record).map((rea: any) => {
          if (rea.indexOf('vpmk') != -1) {
            let steac = deepCopy(Number(data.record[rea]));
            if (isNullPm(steac)) steac = 0;
            mun.push(steac);
          }
        });
        mun.sort((a, b) => {
          a > b ? (min = b) : (min = a);
        });
        return min;
      },
    };
    steamB.push(steamCR);
    steamB.push(steamMAX);
    steamB.push(steamMIN);
    base.columnsB = steamB;
  };

  /**
   * @exports addInspection 创建新检验
   */
  const addInspection = (): any => {
    const steam: any = {
      ihead: {
        startTime: formatDate(new Date(), 'yyyy-MM-dd'),
        mb002: base.cloneSteam.pm,
        mb003: base.cloneSteam.gg,
        ta001: base.cloneSteam.singetsu,
        ta002: base.cloneSteam.odd,
        ta004: base.cloneSteam.gy,
        ta006: base.cloneSteam.pinhao,
        ta015: base.cloneSteam.ta015,
        ta024: base.cloneSteam.ta024,
        udf01: base.cloneSteam.udf01,
        udf66: base.inspectionQuantity,
        udf88: base.inspectionQuantity,
        people: isNullPm(localStorage.getItem('LOGININFO')) ? '未知' : JSON.parse(localStorage.getItem('LOGININFO') as any).MV002.trim(),
        udf06: base.headNpm.udf06,
        result: base.reaca == 'NG' ? 'Y' : 'N',
        type: router.currentRoute.value.query.TYPENAME == '过程检验' ? 'courseInspect' : 'restockInspect ',
      },
      ibodyList: [],
      ibasicsList: [],
      code: router.currentRoute.value.query.code,
    };
    let bocam = false;
    base.numericalTypeList.map((res: any) => {
      for (let a = 0; a <= base.inspectionQuantity - 1; a++) {
        if (isNullPm(res['vpmk' + (a + 1)])) {
          bocam = true;
          break;
        }
      }
    });
    // if (bocam) {
    //   notification.info('有参数未检验,请检查确认');
    //   return false;
    // }

    console.log(base.textYypeList);

    base.textYypeList.map((res: any) => {
      const steamN: any = Object.keys(res);
      const steamListA: any = [];
      steamN.map((reb: any) => {
        if (reb.indexOf('vpmk') != -1) {
          if (isNullPm(res[reb])) {
            res[reb] = '/';
          }
          steamListA.push(res[reb]);
        }
      });


      const constm: any = {
        mg003: res.mg003,
        values: steamListA,
      };
      steam.ibodyList.push(res);
      steam.ibasicsList.push(constm);
    });
    base.numericalTypeList.map((res: any) => {
      const steamN: any = Object.keys(res);
      const steamListA: any = [];
      steamN.map((reb: any) => {
        if (reb.indexOf('vpmk') != -1) {
          if (isNullPm(res[reb])) {
            res[reb] = 0;
          }
          steamListA.push(res[reb]);
        }
      });

      const constm: any = {
        mg003: res.mg003,
        values: steamListA,
      };
      steam.ibodyList.push(res);
      steam.ibasicsList.push(constm);
    });

    console.log(steam, '==>addInspection');


    qmsmgAdd(steam).then((res: any) => {
      notification.info(res.message);
      if (res.code == 200) {
        router.push('/inspectionDetailsList');
        // location.reload();
      }
    });
  };

  /**
   * @exports cameraActivate 调起扫码的方法
   */
  const cameraActivate = () => {
    router.push('cameraTemplate');
  };

  const renderedHandler = () => {
    console.log('渲染完成');
  };
  const errorHandler = () => {
    console.log('渲染失败');
  };

  const pdfLoad = () => {};

  const checkedValueChange = (param: any) => {
    base.checkedUrlValue = param.url;
  };

  /**
   * @exports pinBind
   */
  const pinBind = () => {
    const steam = [
      {
        value: 'OK',
        label: 'OK',
      },
    ];
  };

  //存储当前页面数据
  const reserve=()=>{
    let obj={
      textYypeList:base.textYypeList,
      numericalTypeList:base.numericalTypeList
    };
    localStorage.setItem('qualityAssuranceDetailData',JSON.stringify(obj));
    notification.info('保存成功');
  };

  return {
    handlePageChange,
    handlePageSizeChange,
    base,
    viewDetails,
    viewInspect,
    init,
    textChange,
    cameraActivate,
    addInspection,
    renderedHandler,
    errorHandler,
    pdfLoad,
    checkedValueChange,
    reserve,
  };
}
